using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CoreLibrary;
using CoreLibrary.Sql;
using IBBI.DataBase.Persistent;

namespace IBBI.DataBase.Impl.Sql {

    internal class SelectDescendants : ISqlQuery<List<Category>> {

        private readonly int _left;
        private readonly int _right;
        private readonly string _tableName;

        public SelectDescendants(int left, int right, string tableName) {
            _left  = left;
            _right = right;
            _tableName = tableName;
        }

        public string GetSQL() {
            return string.Format(
                @"
                SEELCT node.* 
                FROM {0} AS node
                WHERE node.LID BETWEEN @left AND @right
                ORDER BY node.LID", _tableName);
        }

        public void SetParameters(SqlCommand command) {
            command.Parameters.AddWithValue("@left",  _left);
            command.Parameters.AddWithValue("@right", _right);
        }

        public List<Category> GetResult (SqlConnection conn, SqlDataReader result) {
            var cats = new List<Category>();
            if (result.HasRows) {
                cats.Add(ReadCatalog(result));
            }
            return cats;
        }

        private static Category ReadCatalog (SqlDataReader result) {
            return new Category {
                Id          = (int)result["ID"],
                LID         = (int)result["LID"],
                RID         = (int)result["RID"],
                PID         = (int)result["PID"],
                Level       = (int)result["LEVEL"],
                Name        = Util.GetString(result["NAME"]),
                Type        = (int)result["TYPE"],
                Thumb       = Util.GetString(result["THUMB"]),
                Title       = Util.GetString(result["TITLE"]),
                Description = Util.GetString(result["DESCRIPTION"]),
                Keywords    = Util.GetString(result["KEYWORDS"]),
                Enable      = (bool)result["ENABLE"],
                ListOrder   = (int)result["LIST_ORDER"],
                DateCreated = (DateTime)result["DATE_CREATED"],
                DateUpdated = (DateTime)result["DATE_UPDATED"]
            };
        }
    }
}